from rest_framework import serializers
from dvadmin.utils.serializers import CustomModelSerializer
from .models import PurchasePlan, PurchaseDetail
from supplier.models import SupplierProduct
from supplier.serializers import SupplierProductSerializer

class PurchaseDetailSerializer(CustomModelSerializer):
    """采购明细序列化器"""
    product_data = SupplierProductSerializer(source='product', read_only=True)
    
    class Meta:
        model = PurchaseDetail
        fields = "__all__"
        
class PurchaseDetailCreateUpdateSerializer(CustomModelSerializer):
    """采购明细创建/更新序列化器"""
    
    class Meta:
        model = PurchaseDetail
        fields = '__all__'
        
    def validate(self, attrs):
        """验证和处理产品信息"""
        product = attrs.get('product')
        
        # 如果选择了产品，则自动填充相关字段
        if product:
            attrs['product_name'] = product.product_name
            attrs['product_code'] = product.product_code
            attrs['specification'] = product.specification
            attrs['unit'] = product.unit
            
            # 如果没有手动设置单价，自动填充产品价格
            if 'unit_price' not in attrs or not attrs['unit_price']:
                attrs['unit_price'] = product.price
                
            # 计算金额
            if 'quantity' in attrs and attrs['quantity']:
                attrs['amount'] = attrs['quantity'] * attrs['unit_price']
        
        return attrs

class PurchasePlanSerializer(CustomModelSerializer):
    """采购计划序列化器"""
    details = PurchaseDetailSerializer(many=True, read_only=True, source='purchasedetail_set')
    
    class Meta:
        model = PurchasePlan
        fields = "__all__"

class PurchasePlanCreateUpdateSerializer(CustomModelSerializer):
    """采购计划创建/更新序列化器"""
    details = PurchaseDetailCreateUpdateSerializer(many=True, required=False)
    
    class Meta:
        model = PurchasePlan
        fields = '__all__'

    def create(self, validated_data):
        details_data = validated_data.pop('details', None)
        instance = super().create(validated_data)
        
        if details_data:
            for detail in details_data:
                PurchaseDetail.objects.create(plan=instance, **detail)
                
        return instance

    def update(self, instance, validated_data):
        details_data = validated_data.pop('details', None)
        instance = super().update(instance, validated_data)
        
        if details_data is not None:
            # 删除原有明细
            instance.purchasedetail_set.all().delete()
            # 创建新的明细
            for detail in details_data:
                PurchaseDetail.objects.create(plan=instance, **detail)
                
        return instance